package com.wzw.basics.concurrent.thread;

import java.util.logging.Logger;

/**
 * 死锁
 */
public class Deadlock {
    // 锁资源
    public static final Object resource1 = new Object();
    public static final Object resource2 = new Object();

    private static final Logger LOGGER = Logger.getLogger("Deadlock");

    public static Thread thread1() {
        return new Thread(() -> {
            synchronized (resource1) {
                LOGGER.info(Thread.currentThread().getName() + " get resource1");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LOGGER.info(Thread.currentThread() + " wait resource2");
                synchronized (resource2) {
                    LOGGER.info(Thread.currentThread().getName() + " get resource2");
                }
            }
        });
    }

    public static Thread thread2() {
        return new Thread(() -> {
            synchronized (resource2) {
                LOGGER.info(Thread.currentThread().getName() + " get resource2");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LOGGER.info(Thread.currentThread().getName() + " wait resource1");
                synchronized (resource1) {
                    LOGGER.info(Thread.currentThread().getName() + " get resource1");
                }
            }
        });
    }

    public static void start() {
        Thread thread1 = thread1();
        thread1.start();
        Thread thread2 = thread2();
        thread2.start();
    }
}
